﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Aspose.Cells;
using System.IO;
using msBsc.AppLogic.DataAlc;

namespace msBsc.WebUi
{
    public partial class wfCommercialTenantInfo : msBsc.Cls.BPageHt
    {

        //CBizShpCommercialTenantInfo objShpCommercialTenantInfo = new CBizShpCommercialTenantInfo();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControls();
                //System.Random rd = new Random();
                //sRadom.Value = this.GetRadomString();
            }
        }

        private void BindControls()
        {
            if (!IsPostBack)
            {

            }
        }
        //重构基类的回调处理函数，以strAction属性来判断是什么类型的回调，该变量的值对应前台的ACTION参数，如：按钮的名称等
        public override void InitialByParam()
        {
            if (this.gtGridRet != null)
            {
                if (this.gtGridRet.action == "load" || this.gtGridRet.action == "export")//处理GRID的数据原获取和数据导出
                {
                    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                    if (ds != null && ds.Tables.Count > 0)
                        SetReturnDatatable(ds.Tables[0], "CUSTOMER_REGISTER_ID");//CONSTANT_CATEGORY_ID为表的KEY字段，可填可不填
                }
                //处理数据保存
                if (this.gtGridRet.action == "save" && (gtGridRet.insertedRecords.Length > 0 || gtGridRet.updatedRecords.Length > 0 || gtGridRet.deletedRecords.Length > 0))
                {
                    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                    try
                    {
                        if (ds != null && ds.Tables.Count > 0)
                        {

                            //处理记录更新，前台已传入更新的ROW
                            for (int i = 0; i < gtGridRet.updatedRecords.Length; i++)
                            {
                                string stridtm = gtGridRet.updatedRecords[i]["CUSTOMER_REGISTER_ID"].ToString();
                                if (stridtm != string.Empty)
                                {
                                    DataRow[] arrtemr = ds.Tables[0].Select("CUSTOMER_REGISTER_ID='" + stridtm + "'");
                                    if (arrtemr.Length > 0)
                                    {
                                        msBsc.AppLogic.Cfg.HttpTools.CopyHashToDataRow(gtGridRet.updatedRecords[i], arrtemr[0]);
                                    }
                                }
                            }

                            //处理记录删除，前台已传入删除的ROW
                            for (int i = 0; i < gtGridRet.deletedRecords.Length; i++)
                            {
                                string stridtm = gtGridRet.deletedRecords[i]["CUSTOMER_REGISTER_ID"].ToString();
                                if (stridtm != string.Empty)
                                {
                                    DataRow[] arrtemr = ds.Tables[0].Select("CUSTOMER_REGISTER_ID='" + stridtm + "'");
                                    if (arrtemr.Length > 0)
                                    {
                                        arrtemr[0].Delete();
                                    }
                                }
                            }
                            if (ds.HasChanges())
                            {
                                System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                                transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                                transactionOption.Timeout = new TimeSpan(0, 10, 0);
                                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                                {

                                    using (msBsc.AppLogic.DataAlc.CBizCustomerRegister objtem1 = new msBsc.AppLogic.DataAlc.CBizCustomerRegister())
                                    {
                                        objtem1.Update(ds);
                                    }



                                    //objBseDataSyn.Update(ds, "PROJECT_NME,CLASS_NME,TO_SERVER_NME", false);
                                    ds.AcceptChanges();

                                    ts.Complete();
                                    ts.Dispose();

                                    //using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
                                    //{
                                    //    string strmtem111 = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase;
                                    //    System.Web.Routing.RouteTable.Routes.Clear();
                                    //    System.Data.DataSet ds2 = oCDbAccess.QueryBySQL("SELECT USER_NME,LEVEL_ONE_NME,SHOW_PAGE_URL FROM SHP_GOODS_TYPE_LEVEL_ONE");
                                    //    for (int i = ds2.Tables[0].Rows.Count - 1; i >= 0; i--)
                                    //    {
                                    //        System.Web.Routing.RouteTable.Routes.Add("myRoute" + i.ToString(), new System.Web.Routing.Route(ds2.Tables[0].Rows[i]["SHOW_PAGE_URL"].ToString(), new System.Web.Routing.PageRouteHandler("~" + strmtem111 + (ds2.Tables[0].Rows[i]["OLD_URL"].ToString().StartsWith("/") ? ds2.Tables[0].Rows[i]["OLD_URL"].ToString().Substring(1) : ds2.Tables[0].Rows[i]["OLD_URL"].ToString()))));
                                    //    }
                                    //} 
                                }
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        ds.RejectChanges();
                        gtGridRetSaveException = err.Message;
                    }
                }
                if (gtGridRetSaveSuccess && (this.gtGridRet.action == "save" || strAction == "btnSave"))//根据传入的回调类型进行处理，这里响应编辑按钮
                {
                    //保存后将页面置为查看状态
                    SetMode("VIEW");
                }
            }
            else if (strAction == "btnEdit")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetMode("EDIT");
            }
            else if (strAction == "btnNotSave")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetMode("VIEW");
            }
            else if (strAction == "btnConfirm")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetItemStatus(this.GetParamHtValue("CHECK_ID"), "True");
                this.ExecJScript("btnDo('mFinder');");
            }
            else if (strAction == "btnCancel")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetItemStatus(this.GetParamHtValue("CHECK_ID"), "False");
                this.ExecJScript("btnDo('mFinder');");
            }

            base.InitialByParam();
        }
        private void SetItemStatus(string strIds, string strStatus)
        {
            using (msBsc.AppLogic.DataAlc.CBizSysUser objCBizSysUser = new AppLogic.DataAlc.CBizSysUser())
            {
                DataSet ds = objCBizSysUser.SelectByIds(strIds);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["REC_ACTIVE"].ToString() != strStatus)
                    {
                        ds.Tables[0].Rows[i]["REC_ACTIVE"] = strStatus == "True";
                    }
                }
                if (ds.HasChanges())
                {
                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        objCBizSysUser.Update(ds);
                        ds.AcceptChanges();

                        ts.Complete();
                        ts.Dispose();
                    }
                }
            }
        }

        //修改页面状态
        private void SetMode(string strMode)
        {
            EditMode = strMode; switch (strMode)
            {
                case "EDIT":
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnNotSave", true);
                    EnabledLinkBtn("btnConfirm", false);
                    EnabledLinkBtn("btnCancel", false);
                    this.ExecJScript("doEditGt('myGrid1');");
                    break;
                case "ADD":
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnNotSave", false);
                    EnabledLinkBtn("btnConfirm", false);
                    EnabledLinkBtn("btnCancel", false);
                    this.ExecJScript("doEditGt('myGrid1');");
                    break;
                case "VIEW":
                    EnabledLinkBtn("btnEdit", true);
                    EnabledLinkBtn("btnSave", false);
                    EnabledLinkBtn("btnNotSave", false);
                    EnabledLinkBtn("btnConfirm", true);
                    EnabledLinkBtn("btnCancel", true);
                    this.ExecJScript("doCancelGt('myGrid1');");
                    break;
            }
        }
        //获取数据原,"DP_DATA"字符一定不要改变，否则系统不能自动清除缓存
        public DataSet GetDisplayData(string strgtGridID, string strSrcF, string strsRadom)
        {
            if (strgtGridID == "myGrid1")
            {
                DataSet ds;
                if (strSrcF == "mFinder" || !this.SessionIsExists(strsRadom + "DP_DATA", "1"))//点击查询按钮时，或需要数据而没有缓存时，根据条件取出数据记录
                {
                    using (msBsc.AppLogic.DataAlc.CBizCustomerRegister objCBizCustomerRegister = new CBizCustomerRegister())
                    {
                        string parmValue = this.GetParamHtValue("USER_NME") == string.Empty ? "" : "%" + this.GetParamHtValue("USER_NME") + "%";
                        string parmValue1 = this.GetParamHtValue("UTYP_ACTIVE");
                        string parmValue2 = this.GetParamHtValue("SELECTEMP");



                        ds = objCBizCustomerRegister.GetUserInfoByConditions(parmValue1, this.GetParamHtValue("START_TIME"), this.GetParamHtValue("STOP_TIME"), parmValue, parmValue2);


                        ds.Tables[0].TableName = "DJK_CUSTOMER_REGISTER";

                        ds.AcceptChanges();
                    }
                    SetSession(strsRadom + "DP_DATA", ds, "1");
                    //查询时，将页面置为查看状态
                    if (strSrcF == "mFinder")
                        SetMode("VIEW");
                }
                else
                {
                    ds = (DataSet)this.GetSession(strsRadom + "DP_DATA", "1");
                }
                return ds;
            }
            else
            {
                return null;
            }
        }


        public override void DoAction()
        {
            if (this.strAction == "getEmployee")
            {
                SetEmployeeList();
            }
            if (this.strAction == "AreaChange")
            {
                //AreaChange();
                //CreateExcel(GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom), "1", "test");
            }

            if (this.strAction == "InsertIntoExcel")
            {
                string fileName = ToExcel(GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom));
                this.ExecJScript(@"SetDownLoadAddr('" + fileName + "');");
            }
        }

        private void SetEmployeeList()
        {
            DataSet ds;
            using (msBsc.AppLogic.DataAlc.CBizEmployeeInfo objCBizEmployeeInfo = new CBizEmployeeInfo())
            {
                ds = objCBizEmployeeInfo.GetAllEmployee();
            }
            string retJson = msBsc.AppLogic.Cfg.HttpTools.GetJsonByTable(ds.Tables[0], "", "", 1, 500, "");
            this.ExecJScript(@"
                            var _html = $('#employee_info').html();

                            laytpl(_html).render(" + retJson + @", function (render) {
                                $('#dplINVATE_ACTIVE').html(render);
                            });");
        }

        private void AreaChange()
        {
            using (msBsc.AppLogic.DataAlc.CBizCustomerBaseInfo objCBizCustomerBaseInfo = new CBizCustomerBaseInfo())
            {
                DataSet ds = objCBizCustomerBaseInfo.DataObj.QueryBySQL(@"select * from DJK_CUSTOMER_BASEINFO");
                DataSet dsarea = objCBizCustomerBaseInfo.DataObj.QueryBySQL(@"select * from djk_country_city");
                for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
                {
                    for (int j = dsarea.Tables[0].Rows.Count - 1; j >= 0; j--)
                    {
                        if (dsarea.Tables[0].Rows[j]["COUNTRY_CITY_ID"].ToString() == ds.Tables[0].Rows[i]["CUSTOMER_DISTINATION_ID"].ToString())
                        {
                            ds.Tables[0].Rows[i]["CUSTOMER_CITY_ID"] = dsarea.Tables[0].Rows[j]["PARENTID_FOR_CITY"];
                        }
                    }

                    if (ds.Tables[0].Rows[i]["CUSTOMER_BASEINFO_GENDER"] == DBNull.Value)
                    {
                        ds.Tables[0].Rows[i]["CUSTOMER_BASEINFO_GENDER"] = "";
                    }
                }

                ds.Tables[0].TableName = objCBizCustomerBaseInfo.TableName;

                objCBizCustomerBaseInfo.Update(ds);
                this.ExecJScript("alert('aaaa')");
            }
        }

        //Aspose.Cells 导入导出EXCEL
        //2011-07-01 17:00
        /// <summary>
        /// 导出方法
        /// </summary>
        /// <param name="ds">信息二</param>
        public string ToExcel(DataSet ds)
        {

            Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();
            //删除文件夹下所有文件
            DeleteAllFile(new System.IO.DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(@"~\Excel")), false);
            //生成文件名
            string fileName = "用户数据" + DateTime.UtcNow.ToString("yyyy_MM_dd");
            //判断文件是否存在
            if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(@"~\Excel\" + fileName + ".xlsx")))
            {
                //创建文件
                File.Create(System.Web.HttpContext.Current.Server.MapPath(@"~\Excel\" + fileName + ".xlsx")).Close();
            }

            wk.Open(System.Web.HttpContext.Current.Server.MapPath(@"~\Excel\" + fileName + ".xlsx"));
            SetWorkSheetHeader(wk.Worksheets[0], ds.Tables[0].Columns);
            AddExcelSHeet(wk, ds);
            wk.Save(System.Web.HttpContext.Current.Server.MapPath(@"~\Excel\" + fileName + ".xlsx"));
            return fileName;
        }

        /// <summary>
        /// 导出增加信息二
        /// </summary>
        /// <param name="cells">当前EXCEL SHEET行号<</param>
        /// <param name="ds">信息内容</param>
        private void AddExcelSHeet(Aspose.Cells.Workbook wk, DataSet ds)
        {
            if (ds != null)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                    {
                        wk.Worksheets[0].Cells[i + 1, j].PutValue(ds.Tables[0].Rows[i][j]);
                    }
                }
            }
        }

        private void SetEvenOrOddColor(Aspose.Cells.Worksheet ws, int TotalDataRow, bool IsOddStyle)
        {

        }

        /// <summary>
        /// 设置表头内容
        /// </summary>
        /// <param name="ws"></param>
        /// <param name="tbColumns"></param>
        private void SetWorkSheetHeader(Aspose.Cells.Worksheet ws, System.Data.DataColumnCollection tbColumns)
        {
            if (tbColumns.Count <= 0)
            {
                return;
            }

            for (int i = 0; i < tbColumns.Count; i++)
            {
                ws.Cells[0, i].PutValue(tbColumns[i].ColumnName);
            }
        }

        /// <summary>
        /// 删除文件夹下所有文件
        /// </summary>
        /// <param name="filePath">文件夹路径</param>
        /// <param name="delWithChilFileBag">是否删除所有子文件夹文件</param>
        private void DeleteAllFile(System.IO.DirectoryInfo filePath, bool delWithChilFileBag)
        {
            if (delWithChilFileBag)
            {
                foreach (System.IO.DirectoryInfo d in filePath.GetDirectories())
                {
                    DeleteAllFile(d, delWithChilFileBag);
                }
            }

            foreach (System.IO.FileInfo f in filePath.GetFiles())
            {
                if (f.Name.Contains("用户数据") && f.Extension.Contains("xls"))
                {
                    f.Delete();
                }
            }
        }
    }
}